package com.hw01.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.hw01.common.Result;
import com.hw01.constant.DelState;
import com.hw01.entity.EmployeeWorkloads;
import com.hw01.entity.TaskAllocation;
import com.hw01.mapper.EmployeeWorkloadsMapper;
import com.hw01.mapper.TaskAllocationMapper;
import com.hw01.service.EmployeeWorkloadsService;
import com.hw01.utils.DateUtils;
import com.hw01.utils.OSSUtils;
import com.hw01.vo.EmployeeWorkloadsSumVo;
import com.hw01.vo.EmployeeWorkloadsVo;

/**
 * <p>
 * 员工工作量 服务实现类
 * </p>
 *
 * @author zhong
 * @since 2024-03-18
 */
@Service
public class EmployeeWorkloadsServiceImpl extends ServiceImpl<EmployeeWorkloadsMapper, EmployeeWorkloads> implements EmployeeWorkloadsService {

    @Autowired
    private EmployeeWorkloadsMapper mapper;

    @Autowired
    private TaskAllocationMapper taskAllocationMapper;

    @Override
    public Result<List<EmployeeWorkloadsVo>> getEmployeeWorkloadsList(Long userId, String year, String month) {
        // 年份
        if (StringUtils.isBlank(year)) {
            year = DateUtils.getYear();
        }

        // 月份
        month = DateUtils.mendMonth(month);

        MPJLambdaWrapper<EmployeeWorkloads> wrapper = new MPJLambdaWrapper<EmployeeWorkloads>()
            .eq(EmployeeWorkloads::getUserId, userId).eq(EmployeeWorkloads::getYear, year)
            .eq(EmployeeWorkloads::getMonth, month).eq(EmployeeWorkloads::getDelState, DelState.UNDELETED);

        List<EmployeeWorkloadsVo> list = mapper.selectJoinList(EmployeeWorkloadsVo.class, wrapper);

        return Result.success("查询成功", list);
    }

    @Override
    public Result<EmployeeWorkloadsSumVo> getEmployeeWorkloads(Long userId, String year, String month) {

        // 年份
        if (StringUtils.isBlank(year)) {
            year = DateUtils.getYear();
        }

        // 月份
        month = DateUtils.mendMonth(month);

        MPJLambdaWrapper<EmployeeWorkloads> wrapper =
            new MPJLambdaWrapper<EmployeeWorkloads>().selectSum(EmployeeWorkloads::getCommittedWorkloads)
                .eq(EmployeeWorkloads::getUserId, userId).eq(EmployeeWorkloads::getYear, year)
                .eq(EmployeeWorkloads::getMonth, month).eq(EmployeeWorkloads::getDelState, DelState.UNDELETED);

        EmployeeWorkloadsSumVo vo = mapper.selectJoinOne(EmployeeWorkloadsSumVo.class, wrapper);

        TaskAllocation ta = taskAllocationMapper
            .selectOne(new LambdaQueryWrapper<TaskAllocation>().eq(TaskAllocation::getDelState, DelState.UNDELETED)
                .eq(TaskAllocation::getUserId, userId).eq(TaskAllocation::getMonth, month));

        Integer workloads;
        if (ta != null && ta.getWorkloads() != null) {
            workloads = ta.getWorkloads();
        } else {
            workloads = 100;
        }

        if (vo == null) {
            vo = new EmployeeWorkloadsSumVo();
            vo.setCommittedWorkloads(0);
        }

        vo.setWorkloads(workloads);

        return Result.success("查询成功", vo);
    }

    @Override
    public Result<Boolean> committedWorkloads(Long userId, LocalDate submissionDate, Byte committedWorkloads) {
        if (submissionDate == null) {
            submissionDate = LocalDate.now();
        }

        // 年份
        String year = DateUtils.getYear(submissionDate);

        // 月份
        String month = DateUtils.getMonth(submissionDate);

        EmployeeWorkloads ew = mapper.selectOne(
            new LambdaQueryWrapper<EmployeeWorkloads>().eq(EmployeeWorkloads::getDelState, DelState.UNDELETED)
                .eq(EmployeeWorkloads::getUserId, userId).eq(EmployeeWorkloads::getSubmissionDate, submissionDate));

        if (ew == null) {
            // 新增
            ew = new EmployeeWorkloads();
            ew.setCommittedWorkloads(committedWorkloads);
            ew.setUserId(userId);
            ew.setYear(year);
            ew.setMonth(month);
            ew.setSubmissionDate(submissionDate);
            ew.setCreator(userId);
            ew.setCreateTm(LocalDateTime.now());
            ew.setModifier(userId);
            ew.setModifyTm(LocalDateTime.now());
            ew.setDelState(DelState.UNDELETED);

            mapper.insert(ew);
        } else {
            // 修改
//            LambdaUpdateWrapper<EmployeeWorkloads> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.set(EmployeeWorkloads::getCommittedWorkloads, committedWorkloads);
//            updateWrapper.set(EmployeeWorkloads::getModifier, userId);
//            updateWrapper.set(EmployeeWorkloads::getModifyTm, LocalDateTime.now());
//            updateWrapper.eq(EmployeeWorkloads::getId, ew.getId());
//
//            mapper.update(null, updateWrapper);
            // 如果今日已有提交，则禁止修改并返回错误消息
            return Result.error("今日的工作量已提交，不允许修改或重复提交");
        }

        return Result.success("提交工作量成功", Boolean.TRUE);
    }

    @Override
    public Result<String> leaderVerify(Long id, MultipartFile file) {
        // 文件名
        String fileName = file.getOriginalFilename();

        if (StringUtils.isBlank(fileName)) {
            return Result.error("输入的文件错误");
        }

        String[] fileNames = fileName.split("[.]");
        String suffix = fileNames[fileNames.length - 1];

        // oss路径，包括文件名
        String objectName = id + "_" + System.currentTimeMillis() + "." + suffix;
        String url = null;
        try (InputStream is = file.getInputStream()) {
            // 上传到OSS
            url = OSSUtils.upload(is, objectName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isNotBlank(url)) {
            LambdaUpdateWrapper<EmployeeWorkloads> updateWrapper =
                new LambdaUpdateWrapper<EmployeeWorkloads>().set(EmployeeWorkloads::getLeaderCertain, true)
                    .set(EmployeeWorkloads::getProofPictureUrl, url).eq(EmployeeWorkloads::getId, id);

            mapper.update(null, updateWrapper);

            return Result.success("队长确认工作量成功");
        } else {
            return Result.error("队长确认工作量失败");
        }
    }

}
